// API服务层
import { API_CONFIG, getApiConfig } from '@/config/api'

export interface PathSource {
  id: string
  type: 'hlsSource' | 'redirect' | 'rpiCameraSource' | 'rtmpConn' | 'rtmpSource' | 'rtspSession' | 'rtspSource' | 'rtspsSession' | 'srtConn' | 'srtSource' | 'mpegtsSource' | 'rtpSource' | 'webRTCSession' | 'webRTCSource'
}

export interface PathReader {
  id: string
  type: 'hlsMuxer' | 'rtmpConn' | 'rtspSession' | 'rtspsSession' | 'srtConn' | 'webRTCSession'
}

export interface Path {
  source: PathSource | null
  name: string
  confName: string
  ready: boolean
  readyTime: string | null
  bytesReceived: number
  bytesSent: number
  readers: PathReader[]
  tracks: string[]
}

export interface PathList {
  pageCount: number
  itemCount: number
  items: Path[]
}

export interface ApiError {
  error: string
}

// 录像相关接口
export interface RecordingSegment {
  start: string
}

export interface Recording {
  name: string
  segments: RecordingSegment[]
}

// 新的录像查询接口
export interface RecordingFile {
  start: string
  duration: number
  url: string
}

export interface RecordingListResponse {
  recordings: RecordingFile[]
}

// API配置
const API_BASE_URL = getApiConfig().API_BASE_URL
const STREAM_BASE_URL = getApiConfig().STREAM_URL
const WEBRTC_BASE_URL = getApiConfig().WEBRTC_URL
const RECORDINGS_BASE_URL = getApiConfig().RECORDINGS_URL
const API_ENDPOINTS = API_CONFIG.ENDPOINTS

// 摄像头接口
export class CameraApiService {
  private baseUrl: string

  constructor(baseUrl: string = API_BASE_URL) {
    this.baseUrl = baseUrl
  }

  /**
   * 获取摄像头路径列表
   * @param page 页码
   * @param itemsPerPage 每页数量
   */
  async getPathsList(page: number = 0, itemsPerPage: number = 100): Promise<PathList> {
    try {
      const url = new URL(API_ENDPOINTS.PATHS_LIST, this.baseUrl)
      url.searchParams.set('page', page.toString())
      url.searchParams.set('itemsPerPage', itemsPerPage.toString())

      const response = await fetch(url.toString(), {
        method: 'GET',
      })

      if (!response.ok) {
        const errorData: ApiError = await response.json()
        throw new Error(errorData.error || `HTTP error! status: ${response.status}`)
      }

      const data: PathList = await response.json()
      return data
    } catch (error) {
      console.error('获取摄像头列表失败:', error)
      throw error
    }
  }

  /**
   * 生成视频流URL
   * @param pathName 路径名称
   */
  getStreamUrl(pathName: string): string {
    return `${STREAM_BASE_URL}/${pathName}`
  }

  /**
   * 生成HLS流URL - 支持直接HLS流播放
   * @param pathName 路径名称
   */
  getHlsStreamUrl(pathName: string): string {
    return `${STREAM_BASE_URL}/${pathName}`
  }

  /**
   * 生成WebRTC流URL
   * @param pathName 路径名称
   */
  getWebRtcStreamUrl(pathName: string): string {
    return `${WEBRTC_BASE_URL}/${pathName}`
  }

  /**
   * 生成WebRTC WHEP URL
   * @param pathName 路径名称
   */
  getWebRtcWhepUrl(pathName: string): string {
    return `${WEBRTC_BASE_URL}/${pathName}/whep`
  }


  /**
   * 获取指定摄像头的录像文件列表
   * @param cameraName 摄像头名称
   */
  async getRecordings(cameraName: string): Promise<Recording> {
    try {
      const url = `${this.baseUrl}${API_ENDPOINTS.RECORDINGS_GET}/${encodeURIComponent(cameraName)}`

      const response = await fetch(url, {
        method: 'GET',
      })

      if (!response.ok) {
        const errorData: ApiError = await response.json()
        throw new Error(errorData.error || `HTTP error! status: ${response.status}`)
      }

      const data: Recording = await response.json()
      return data
    } catch (error) {
      console.error('获取录像列表失败:', error)
      throw error
    }
  }

  /**
   * 获取指定时间范围内的录像列表（新接口）
   * @param path 摄像头路径
   * @param start 开始时间 (ISO 8601格式)
   * @param end 结束时间 (ISO 8601格式)
   */
  async getRecordingsByTimeRange(path: string, start: string, end: string): Promise<RecordingFile[]> {
    try {
      const url = new URL(API_ENDPOINTS.RECORDINGS_LIST, RECORDINGS_BASE_URL)
      url.searchParams.set('path', path)
      url.searchParams.set('start', start)
      url.searchParams.set('end', end)

      const response = await fetch(url.toString(), {
        method: 'GET',
      })

      if (!response.ok) {
        const errorData: ApiError = await response.json()
        throw new Error(errorData.error || `HTTP error! status: ${response.status}`)
      }

      const data: RecordingFile[] = await response.json()
      return data
    } catch (error) {
      console.error('获取时间范围录像列表失败:', error)
      throw error
    }
  }

  /**
   * 生成录像下载URL
   * @param path 摄像头路径
   * @param start 开始时间
   * @param duration 持续时间（秒）
   */
  getRecordingDownloadUrl(path: string, start: string, duration: number): string {
    const url = new URL(API_ENDPOINTS.RECORDINGS_DOWNLOAD, RECORDINGS_BASE_URL)
    url.searchParams.set('path', path)
    url.searchParams.set('start', start)
    url.searchParams.set('duration', duration.toString())
    return url.toString()
  }
}

// 创建API服务实例
export const cameraApi = new CameraApiService()

// 摄像头数据转换器
export class CameraDataConverter {
  /**
   * 将API返回的Path数据转换为前端使用的Camera数据
   */
  static pathToCamera(path: Path, baseUrl: string = API_BASE_URL): Camera {
    return {
      id: path.name,
      name: path.name,
      status: path.ready ? 'online' : 'offline',
      streamUrl: `${WEBRTC_BASE_URL}/${path.name}`,
      confName: path.confName,
      readyTime: path.readyTime,
      bytesReceived: path.bytesReceived,
      bytesSent: path.bytesSent,
      readersCount: path.readers.length,
      tracks: path.tracks,
      sourceType: path.source?.type || null
    }
  }

  /**
   * 批量转换Path列表为Camera列表
   */
  static pathsToCameras(paths: Path[], baseUrl: string = API_BASE_URL): Camera[] {
    return paths.map(path => this.pathToCamera(path, baseUrl))
  }

  /**
   * 将API返回的Recording数据转换为前端使用的RecordingItem数据
   */
  static recordingToRecordingItems(recording: Recording, cameraName: string, baseUrl: string = API_BASE_URL): RecordingItem[] {
    return recording.segments.map((segment, index) => {
      const startTime = new Date(segment.start)
      const endTime = new Date(startTime.getTime() + 3600000) // 假设每个片段1小时，实际应该从API获取
      const duration = this.formatDuration(endTime.getTime() - startTime.getTime())

      return {
        id: `${cameraName}_${index}`,
        name: `${cameraName}_${startTime.toISOString().slice(0, 19).replace(/:/g, '-')}.mp4`,
        url: `${STREAM_BASE_URL}/${cameraName}/${segment.start}`,
        startTime: startTime.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        }),
        endTime: endTime.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        }),
        duration: duration,
        size: '未知', // API没有提供大小信息
        type: 'scheduled' as const,
        cameraId: cameraName,
        date: startTime.toISOString().slice(0, 10)
      }
    })
  }

  /**
   * 格式化时长
   */
  private static formatDuration(milliseconds: number): string {
    const hours = Math.floor(milliseconds / 3600000)
    const minutes = Math.floor((milliseconds % 3600000) / 60000)
    const seconds = Math.floor((milliseconds % 60000) / 1000)

    if (hours > 0) {
      return `${hours}小时${minutes}分钟`
    } else if (minutes > 0) {
      return `${minutes}分钟${seconds}秒`
    } else {
      return `${seconds}秒`
    }
  }

  /**
   * 将新的RecordingFile数据转换为前端使用的RecordingItem数据
   */
  static recordingFilesToRecordingItems(recordingFiles: RecordingFile[], cameraName: string): RecordingItem[] {
    return recordingFiles.map((file, index) => {
      const startTime = new Date(file.start)
      const endTime = new Date(startTime.getTime() + file.duration * 1000)
      
      return {
        id: `${cameraName}_${index}`,
        name: `${cameraName}_${this.formatDateTime(startTime)}`,
        url: file.url,
        startTime: this.formatDateTime(startTime),
        endTime: this.formatDateTime(endTime),
        duration: this.formatDurationFromSeconds(file.duration),
        size: '未知', // API没有提供大小信息
        type: 'scheduled' as const,
        cameraId: cameraName,
        date: startTime.toISOString().slice(0, 10)
      }
    })
  }

  /**
   * 格式化日期时间为年月日时分秒格式
   */
  private static formatDateTime(date: Date): string {
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  }

  /**
   * 从秒数格式化时长
   */
  private static formatDurationFromSeconds(seconds: number): string {
    const hours = Math.floor(seconds / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    const secs = Math.floor(seconds % 60)

    if (hours > 0) {
      return `${hours}小时${minutes}分钟`
    } else if (minutes > 0) {
      return `${minutes}分钟${secs}秒`
    } else {
      return `${secs}秒`
    }
  }
}

// 前端使用的Camera接口
export interface Camera {
  id: string
  name: string
  status: 'online' | 'offline'
  streamUrl: string
  confName: string
  readyTime: string | null
  bytesReceived: number
  bytesSent: number
  readersCount: number
  tracks: string[]
  sourceType: string | null
}

// 前端使用的录像项接口
export interface RecordingItem {
  id: string
  name: string
  url: string
  startTime: string
  endTime: string
  duration: string
  size: string
  type: 'motion' | 'scheduled'
  cameraId: string
  date: string
}
